package com.nwpu.coursesupport.service.imple;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nwpu.coursesupport.criteria.ClassRespositorySearchCriteria;
import com.nwpu.coursesupport.criteria.RespositorySearchCriteria;
import com.nwpu.coursesupport.entity.Course;
import com.nwpu.coursesupport.entity.Resource;
import com.nwpu.coursesupport.entity.Respository;
import com.nwpu.coursesupport.entity.bean.JSONResult;
import com.nwpu.coursesupport.enumeration.RoleType;
import com.nwpu.coursesupport.enumeration.Status;
import com.nwpu.coursesupport.mapper.ClassMapper;
import com.nwpu.coursesupport.mapper.CourseMapper;
import com.nwpu.coursesupport.mapper.ResourceMapper;
import com.nwpu.coursesupport.mapper.RespositoryMapper;
import com.nwpu.coursesupport.pagination.PageBounds;
import com.nwpu.coursesupport.service.AbstractService;
import com.nwpu.coursesupport.service.param.IDListParam;
import com.nwpu.coursesupport.service.param.IDParam;
import com.nwpu.coursesupport.service.param.RespositoryServiceParam;
import com.nwpu.coursesupport.view.SCCView;
import com.nwpu.coursesupport.view.mapper.SCCViewMapper;

@Service
public class RespositoryService extends AbstractService{
	
	@Autowired
    private RespositoryMapper respositoryMapper;
	@Autowired
	private ResourceMapper resourceMapper;
	@Autowired
	private CourseMapper courseMapper;
	@Autowired
	private SCCViewMapper sCCViewMapper;
	
    protected static Logger logger = LoggerFactory.getLogger(RespositoryService.class);

	public JSONResult listByClassId(ClassRespositorySearchCriteria sc){
		JSONResult rst=new JSONResult();
		rst.fail();
		
		if(sc==null||sc.getClassId()<=0){
			logger.error("参数有误");
			return rst.fail("参数有误");
		}
		
		if (sc.getPageNo() <= 0){
        	sc.setPageNo(1);
		}
        
        int pageSize = 10;
        int totalCount =this.respositoryMapper.countByClassId(sc);
        int pageCount = totalCount % pageSize > 0 ? totalCount / pageSize + 1 : totalCount / pageSize;
		if (sc.getPageNo() > pageCount){
			sc.setPageNo(pageCount);
		}
		PageBounds page = new PageBounds();
        page.setNumber(sc.getPageNo());
        page.setSize(pageSize);
        
        List<Respository> list = this.respositoryMapper.findByClassId(sc, page);
        if (list == null){
        	logger.error("数据查询失败");
            return rst.fail("数据查询失败");
        }
       
        SCCView view= this.sCCViewMapper.findById(sc.getClassId());
        
        if(view==null){
        	logger.error("该班级不存在");
        	return rst.fail("该班级不存在");
        }
        rst.addData("list", list);
        rst.addData("pageNo", sc.getPageNo());
        rst.addData("allpages",pageCount);
        rst.addData("classView", view);
		rst.success();
		return rst;
	}
	
    public JSONResult list(RespositorySearchCriteria sc) throws Exception{
        JSONResult rst = new JSONResult();
        rst.fail();
       
        if (sc == null||sc.getCourseId()==null){
        	logger.error("参数有误");
        	return rst.fail("参数有误");
        }
        
        if (sc.getPageNo() <= 0){
        	sc.setPageNo(1);
		}
        
        int pageSize = 10;
        int totalCount =this.respositoryMapper.count(sc);
        int pageCount = totalCount % pageSize > 0 ? totalCount / pageSize + 1 : totalCount / pageSize;
		if (sc.getPageNo() > pageCount){
			sc.setPageNo(pageCount);
		}
		PageBounds page = new PageBounds();
        page.setNumber(sc.getPageNo());
        page.setSize(pageSize);
        
        List<Respository> list = this.respositoryMapper.find(sc, page);
        if (list == null){
        	logger.error("数据查询失败");
            return rst.fail("数据查询失败");
        }
        
        rst.addData("list", list);
        rst.addData("courseId", sc.getCourseId());
        rst.addData("pageNo", sc.getPageNo());
        rst.addData("allpages",pageCount );
        rst.success();
        return rst;
    }

    public JSONResult batchCreate(RespositoryServiceParam.BatchCreateParam p) throws Exception{
    	JSONResult rst = new JSONResult();
        rst.fail();
        if(p==null||p.getCourseId()<=0||p.getKeys()==null){
        	logger.error("参数错误");
        	return rst.fail("参数错误");
        }
        
        Course course=this.courseMapper.findById(p.getCourseId());
        if(course==null){
        	logger.error("该课程不存在");
        	return rst.fail("该课程不存在");
        };
        
        List<Resource> list=this.resourceMapper.findByKeys(p.getKeys());
        
        if(list==null||list.size()<=0){
        	logger.error("所上传资源不存在");
        	return rst.fail("所上传资源不存在");
        }
        
        int id=(int) getSession().getAttribute("id");
        String name=(String) getSession().getAttribute("name");
        RoleType roleType=(RoleType) getSession().getAttribute("roleType");
        
        List<Respository> results=new ArrayList<Respository>();
        Respository respository=null;
        Date date=new Date();
        for(Resource r: list){
        	respository=new Respository();
        	
        	respository.setCourseId(p.getCourseId());
            respository.setFileName(r.getFileName());
            respository.setIsQuote(Status.NO);
            respository.setType(r.getFileType());
            respository.setUrl(r.getFileKey());
            respository.setRoleType(roleType);
            respository.setUploaderId(id);
            respository.setUploaderName(name);
            respository.setUploadTime(date);
            results.add(respository);
        }
        try{
        	this.respositoryMapper.batchSave(results);
        }catch(Exception e){
        	//e.printStackTrace();
        	logger.error("批量上传资源失败");
        	return rst.fail("批量上传资源失败");
        }
        
        rst.success();
        return rst;
    }
    
    
 
    public JSONResult create(RespositoryServiceParam.CreateParam p) throws Exception{
        JSONResult rst = new JSONResult();
        rst.fail();
        
        if (p == null){
        	logger.error("参数有误");
            return rst.fail("参数有误");
        }
        
        Course course=this.courseMapper.findById(p.getCourseId());
        if(course==null){
        	logger.error("该课程不存在");
        	return rst.fail("该课程不存在");
        };
        
        Resource resource=this.resourceMapper.findByKey(p.getKey());
        if(resource==null){
        	logger.error("所上传资料不存在，请重新上传");
        	return rst.fail("所上传资料不存在，请重新上传");
        }
        
        int id=(int) getSession().getAttribute("id");
        String name=(String) getSession().getAttribute("name");
        RoleType roleType=(RoleType) getSession().getAttribute("roleType");
        
        Respository respository =new Respository();
        respository.setCourseId(p.getCourseId());
        respository.setFileName(resource.getFileName());
        respository.setIsQuote(Status.NO);
        respository.setType(resource.getFileType());
        respository.setUrl(resource.getFileKey());
        respository.setRoleType(roleType);
        respository.setUploaderId(id);
        respository.setUploaderName(name);
        respository.setUploadTime(new Date());
        
        if (!this.respositoryMapper.save(respository)){
        	logger.error("保存失败");
            return rst.fail("保存失败");
        }
        
        rst.success();
        return rst;
    }


    public JSONResult remove(IDParam p) throws Exception{
        JSONResult rst = new JSONResult();
        rst.fail();
        
        if (p == null || p.getId() <= 0){
        	logger.error("参数有误");
            rst.fail("参数有误");
            return rst;
        }

        
        Respository respository = this.respositoryMapper.findById(p.getId());
        if (respository == null){
        	logger.error("记录不存在或已被删除");
            return rst.fail("记录不存在或已被删除");
        }

        if (!this.respositoryMapper.delete(p.getId())){
        	logger.error("删除失败");
            return rst.fail("删除失败");
        }
        rst.addData("respository", respository);
        rst.success();
        return rst;
    }

    public JSONResult removeAll(IDListParam p) throws Exception{
        JSONResult rst = new JSONResult();
        rst.fail();
        
        if (p == null || p.getIds() == null || p.getIds().isEmpty()){
        	logger.error("参数有误");
            rst.fail("参数有误");
            return rst;
        }
        
        this.respositoryMapper.batchDelete(p.getIds());

        rst.success();
        return rst;
    }

}
